package com.wenzhoujie.fragment;

import java.util.List;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lingou.www.R;
import com.sunday.eventbus.SDBaseEvent;
import com.wenzhoujie.app.AppHelper;
import com.wenzhoujie.baidumap.BaiduMapManager;
import com.wenzhoujie.event.EnumEventTag;
import com.wenzhoujie.http.InterfaceServer;
import com.wenzhoujie.library.dialog.SDDialogConfirm;
import com.wenzhoujie.library.dialog.SDDialogCustom;
import com.wenzhoujie.library.dialog.SDDialogCustom.SDDialogCustomListener;
import com.wenzhoujie.model.IndexActAdvsModel;
import com.wenzhoujie.model.RequestModel;
import com.wenzhoujie.model.act.IndexActNewModel;
import com.wenzhoujie.utils.IocUtil;
import com.wenzhoujie.utils.JsonUtil;
import com.wenzhoujie.utils.SDInterfaceUtil;
import com.wenzhoujie.utils.ViewInject;
import com.wenzhoujie.work.AppRuntimeWorker;

/**
 * 首页fragment
 * 
 * @author js02
 * 
 */
public class HomeFragment2 extends BaseFragment {
	@ViewInject(id = R.id.frag_home_new_ptrsv_all)
	private PullToRefreshScrollView mPtrsvAll = null;

	private HomeTitleBarFragment2 mFragTitle = null;

	private HomeAdvsFragment mFragAdvs = null;
	private HomeIndexFragment mFragIndex = null;
	private HomeZtFragment mFragZt = null;
	private HomeRecommendSupplierFragment mFragRecommendSupplier = null;
	private HomeRecommendEvnetFragment mFragRecommendEvent = null;
	private HomeRecommendDealsFragment mFragRecommendDeals = null;
	private HomeRecommendGuessFragment mFragRecommendGuess = null;

	private IndexActNewModel actModel = null;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.frag_home2, container, false);
		IocUtil.initInjectedView(this, view);
		init();
		return view;
	}

	private void init() {
		locationCity();
		addTitleBarFragment();
		initPullToRefreshScrollView();
		
	}

	private void locationCity()
	{
		BaiduMapManager.getInstance().startLocation(new BDLocationListener()
		{

			@Override
			public void onReceiveLocation(BDLocation location)
			{
				requestIndexAct();
				if (location != null)
				{
					dealLocationSuccess();
				}
				BaiduMapManager.getInstance().stopLocation();
			}

			@Override
			public void onReceivePoi(BDLocation arg0) {
				// TODO Auto-generated method stub
				
			}
		});
	}

	private void dealLocationSuccess()
	{
		String defaultCity = AppRuntimeWorker.getCity_name();
		if (TextUtils.isEmpty(defaultCity))
		{
			return;
		}
		if (!BaiduMapManager.getInstance().hasLocationSuccess())
		{
			return;
		}
		String dist = BaiduMapManager.getInstance().getDistrictShort();
		int cityId = AppRuntimeWorker.getCityIdByCityName(dist);
		if (cityId > 0) // 区域存在于城市列表中
		{
			if (!dist.equals(defaultCity)) // 区域不是默认的
			{
				showChangeLocationDialog(dist);
			}
		} else
		{
			String city = BaiduMapManager.getInstance().getCityShort();
			cityId = AppRuntimeWorker.getCityIdByCityName(city);
			if (cityId > 0) // 城市存在于城市列表中
			{
				if (!city.equals(defaultCity)) // 城市不是默认的
				{
					showChangeLocationDialog(city);
				}
			}else{
				AppRuntimeWorker.setCity_name(city);
			}
		}
	}

	private void showChangeLocationDialog(final String location)
	{
		new SDDialogConfirm().setTextContent("当前定位位置为：" + location + "\n" + "是否切换到" + location + "?").setmListener(new SDDialogCustomListener()
		{

			@Override
			public void onClickConfirm(View v, SDDialogCustom dialog)
			{
				AppRuntimeWorker.setCity_name(location);
			}

			@Override
			public void onClickCancel(View v, SDDialogCustom dialog)
			{
			}

			@Override
			public void onDismiss(DialogInterface iDialog, SDDialogCustom dialog) {
				// TODO Auto-generated method stub
				
			}
		}).show();
	}
	
	private void initPullToRefreshScrollView() {
		// mPtrsvAll.setMode(Mode.PULL_FROM_START);
		mPtrsvAll.setOnRefreshListener(new OnRefreshListener2<ScrollView>() {
			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ScrollView> refreshView) {
				requestIndexAct();
			}

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ScrollView> refreshView) {
			}
		});
		mPtrsvAll.setRefreshing();
	}

	private void requestIndexAct() {

		RequestModel model = new RequestModel();
		model.put("act", "index");
		model.put("city_id", AppRuntimeWorker.getCity_id());
		RequestCallBack<String> handler = new RequestCallBack<String>() {

			@Override
			public void onStart() {

			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				// System.out.println("json数据:"+responseInfo.result);
				/*
				 * try { JSONObject json = new JSONObject(responseInfo.result);
				 * //String name = json.getString("more_list"); // 显示Name //
				 * Toast.makeText(MainActivity.this, name,
				 * Toast.LENGTH_LONG).show(); //
				 * System.out.println("more_list数据:"+name); String name2 =
				 * json.getString("more_list_a"); // 显示Name //
				 * Toast.makeText(MainActivity.this, name,
				 * Toast.LENGTH_LONG).show();
				 * System.out.println("more_list_a数据:"+name2); } catch
				 * (JSONException e) { e.printStackTrace(); }
				 */
				actModel = JsonUtil.json2Object(responseInfo.result,
						IndexActNewModel.class);
				if (!SDInterfaceUtil.isActModelNull(actModel)) {
					if (actModel.getResponse_code() == 1) {
						addFragmentsByActModel(actModel);
					}
				}
			}

			@Override
			public void onFailure(HttpException error, String msg) {

			}

			@Override
			public void onFinish() {
				mPtrsvAll.onRefreshComplete();
			}
		};
		InterfaceServer.getInstance().requestInterface(model, handler);
	}

	protected void addFragmentsByActModel(IndexActNewModel actModel) {
		if (actModel == null) {
			return;
		}
		// 首页广告
		mFragAdvs = new HomeAdvsFragment();
		List<IndexActAdvsModel> listAdvs = actModel.getAdvs();
		// Bundle bundle = new Bundle();
		// bundle.putSerializable(HomeAdvsFragment.EXTRA_LIST_INDEX_ACT_ADVS_MODEL,
		// (Serializable) listAdvs);
		// mFragAdvs.setArguments(bundle);
		mFragAdvs.setListIndexActAdvsModel(listAdvs);
		if (listAdvs.size() > 1) // 如果大于1显示才有意义
		{
			replaceFragment(mFragAdvs, R.id.frag_home_new_fl_advs);
		}

		// 首页分类
		mFragIndex = new HomeIndexFragment();
		mFragIndex.setmIndexModel(actModel);
		replaceFragment(mFragIndex, R.id.frag_home_new_fl_index);

		// 推荐商家
		mFragRecommendSupplier = new HomeRecommendSupplierFragment();
		mFragRecommendSupplier.setmIndexModel(actModel);
		replaceFragment(mFragRecommendSupplier,
				R.id.frag_home_new_fl_recommend_supplier);

		/*
		 * // 推荐活动 mFragRecommendEvent = new HomeRecommendEvnetFragment();
		 * mFragRecommendEvent.setmIndexModel(actModel);
		 * replaceFragment(mFragRecommendEvent,
		 * R.id.frag_home_new_fl_recommend_event);
		 */

		// 首页专题
		mFragZt = new HomeZtFragment();
		mFragZt.setmIndexModel(actModel);
		replaceFragment(mFragZt, R.id.frag_home_new_fl_zt);

		// 推荐团购
		/*
		 * mFragRecommendDeals = new HomeRecommendDealsFragment();
		 * mFragRecommendDeals.setmIndexModel(actModel);
		 * replaceFragment(mFragRecommendDeals,
		 * R.id.frag_home_new_fl_recommend_deals);
		 */
		mFragRecommendGuess = new HomeRecommendGuessFragment();
		mFragRecommendGuess.setmIndexModel(actModel);
		replaceFragment(mFragRecommendGuess,
				R.id.frag_home_new_fl_recommend_guess);

		/*
		 * List<MoreCateActModel> moreLst = actModel.getMore_list_a();
		 * //List<MoreCateActModel> moreLst2 = moreLst.get(0).getCate_info();
		 * if(moreLst==null) { System.out.println("更多列表:null"); } else
		 * System.out.println("更多列表:"+moreLst.get(0).getTop_cate_name());
		 */
	}

	protected void dealFinishRequest() {
		mPtrsvAll.onRefreshComplete();
		AppHelper.hideLoadingDialog();
	}

	private void addTitleBarFragment() {
		mFragTitle = new HomeTitleBarFragment2();
		addFragment(mFragTitle, R.id.frag_home_new_fl_title_bar);
	}

	@Override
	public void onEventMainThread(SDBaseEvent event) {
		// TODO Auto-generated method stub
		super.onEventMainThread(event);
		switch (EnumEventTag.valueOf(event.getEventTagInt())) {
		case CITY_CHANGE:
			requestIndexAct();
			break;
		case RETRY_INIT_SUCCESS:
			dealLocationSuccess();
			break;
		default:
			break;
		}
	}

}